#!/bin/bash

# UDP 服务器地址和端口
UDP_SERVER="127.0.0.1"
UDP_PORT=12345

# 发送 UDP 数据函数
send_udp() {
  local msg_id=$1
  local message=$2
  echo -n -e "$msg_id$message" | nc -u -w1 $UDP_SERVER $UDP_PORT
}

# 获取 CPU 核心数
num=$(nproc)

#### cpu_load ###
# 获取 CPU 负载
cpu_load_average=$(uptime | awk '{print $(NF-2)}' | tr -d ',')
cpu_load_average_num=$(awk "BEGIN { printf \"%.2f\", $cpu_load_average / $num }")
send_udp "\x01" "$cpu_load_average_num"

### memory_user ###
# 获取内存利用率
memory_total=$(free -m | awk '/Mem:/ {print $2}')
memory_used=$(free -m | awk '/Mem:/ {print $3}')
memory_utilization=$(awk "BEGIN { printf \"%.2f\", ($memory_used / $memory_total) * 100 }")
send_udp "\x02" "$memory_utilization"

### disk_usage ###
# 获取根目录的磁盘使用率
disk_usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
send_udp "\x03" "$disk_usage"

### system_uptime ###
# 获取系统运行时间
uptime_seconds=$(awk '{print $1}' /proc/uptime)
send_udp "\x04" "$uptime_seconds"